# Copyright (c) 2022, hzmes and contributors
# For license information, please see license.txt

import frappe
from frappe.model.document import Document
from frappe import _
from srm.srm.erp_sync import K3CloudSync

class ERPSyncConfig(Document):
	def validate(self):
		if len(self.entity_fields) == 0:
			frappe.throw(_("至少需要配置一个表头字段！"))

		l = list(filter(lambda field:field.is_key_field == 1, self.entity_fields))
		if not len(l):
			frappe.throw(_("表头必须配置主键字段！"))
		
		if len(l) > 1:
			frappe.throw(_("表头主键字段必须唯一！"))
   
		sub_table_name_to_field_dic = {}
		for field in self.entry_fields:
			filed_list = []
			if field.table_name in sub_table_name_to_field_dic:
				filed_list = sub_table_name_to_field_dic[field.table_name]
			else:
				sub_table_name_to_field_dic[field.table_name] = filed_list
			filed_list.append(field)

		for table_name,field_list in sub_table_name_to_field_dic.items():
			t = list(filter(lambda field:field.is_foreign_key == 1, field_list))
			if not len(t):
				frappe.throw(_(f"子表[{table_name}]必须配置外键!"))
		
			if len(l) > 1:
				frappe.throw(_(f"子表[{table_name}]外键字段必须唯一！"))


@frappe.whitelist()
def sync_material_from_erp(doc_name):
	sync = K3CloudSync(doc_name)
	sync.sync()